<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\controller\Wxpay;
use app\common\model\CommissionLog;
use app\common\model\Orderproject;
use app\common\model\ViperCard;
use app\common\model\ViperUser;
use app\common\model\Viprecharegtemplate;
use app\common\model\VipRechargeLog;
use Exception;
use think\Db;
use think\Request;
use app\common\controller\Alipay;
use think\facade\Log;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Notify extends Home
{
    public $noNeedLogin = ['*'];

    /**
     * 微信支付回调
     */
    public function wx_notify()
    {

    }

    /**
     * 支付宝支付回调
     */
    public function ali_notify($type)
    {
        switch ($type){
            case '1';
                break;
        }

    }

    /**
     * 会员升级回调
     * @return string
     */
    public function ali_user_up(){
        $getData = $this->request->post();
        Log::write(json_encode($getData));
        $aliPay = new Alipay();
        $status = $aliPay->notify($getData);
        if($status == true){
            //回调成功
            $orderRes = Db::name('qt_recharge_log')
                ->field('rl.*,r.validity,r.type,r.rank_name')
                ->alias('rl')
                ->leftJoin('qt_rank r','r.id = rl.rank_id')
                ->where(['rl.pay_ordersn'=>$getData['out_trade_no']])
                ->find();
            $userInfo = Db::name('qt_users')->where('id',$orderRes['user_id'])->find();
            //账户余额变动记录
            $money['user_id'] = $orderRes['user_id'];
            $money['type'] = '6';
            $money['money'] = $orderRes['total'];
            $money['create_time'] = time();
            $money['content'] = '会员升级';
            $money['check'] = '2';
            $money['flag'] = '1';
            $money['after_money'] = $userInfo['money'] - $orderRes['total'];
            //账户变动记录
            $upLog['user_id'] = $userInfo['id'];
            $upLog['old_rank'] = $userInfo['rank'];
            $upLog['rank_id'] = $orderRes['rank_id'];
            $upLog['type'] = '1';
            $upLog['create_time'] = time();
            //时效会员
            if($orderRes['type'] == '1') {
                $rankTime = date('Y-m-d H:i:s', strtotime("+" . $orderRes['validity'] . "year"));
                $rankTime = strtotime($rankTime);
                try {
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_users')->where('id', $userInfo['id'])->update(['rank_time'=>$rankTime, 'rank' => $orderRes['rank_id']]);
                    Db::name('qt_recharge_log')->where('id', $orderRes['id'])->update(['pay_time' => time(), 'way' =>'1']);
                    Db::name('qt_money_log')->insert($money);
                    Db::name('qt_upgrade_log')->insert($upLog);
                    Db::commit();
                    return "success";
                } catch (Exception $exception) {
                    Db::rollback();
                    return "error";
                }
            }elseif($orderRes['type'] == '2'){
                try{
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_users')->where('id',$userInfo['id'])->update(['rank'=>$orderRes['rank_id']]);
                    Db::name('qt_users')->where('id',$userInfo['id'])->setDec('money',$orderRes['total']);
                    Db::name('qt_recharge_log')->where('id',$orderRes['id'])->update(['pay_time'=>time(),'way'=>'1']);
                    Db::name('qt_money_log')->insert($money);
                    Db::name('qt_upgrade_log')->insert($upLog);
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                    return "error";
                }
                return "success";
            }
        }else{
            //回调失败
            return "error";
        }
    }


    /**
     * 余额充值回调
     * @return string
     */
    public function ali_recharge(){
        $getData = $this->request->post();
        $aliPay = new Alipay();
        $status = $aliPay->notify($getData);
        if($status == true){
            $recharge = Db::name('qt_recharge_log')->where('pay_ordersn',$getData['out_trade_no'])->find();
            $userInfo = Db::name('qt_users')->where('id',$recharge['user_id'])->find();
            //账户余额变动记录
            $money['user_id'] = $userInfo['id'];
            $money['type'] = 3;
            $money['money'] = $recharge['total'];
            $money['create_time'] = time();
            $money['content'] = '';
            $money['check'] = '1';
            $money['flag'] = '1';
            $money['after_money'] = $userInfo['money'] + $recharge['total'];
            try{
                Db::startTrans();
                //修改订单状态
                Db::name('qt_users')->where('id',$userInfo['id'])->setInc('money',$recharge['total']);
                Db::name('qt_recharge_log')->where('id',$recharge['id'])->update(['pay_time'=>time(),'way'=>'1']);
                Db::name('qt_money_log')->insert($money);
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                return "error";
            }
            return "success";
        }
    }

    /**
     * 普通订单回调
     */
    public function ali_order(){
        $getData = $this->request->post();
//        $getData = array (
//            'gmt_create' => '2021-07-14 16:35:40',
//            'charset' => 'utf-8',
//            'seller_email' => 'w13937237266@163.com',
//            'subject' => '测试商品',
//            'sign' => 'fEL7+/XEEE0VQnVv06W/zcrRWYmgL0iKxuKnBwpkrBe5rQpsWpBNt6koxuNdBOZMp77MgVq4PzJMJkPCz+kEqzr9CLaFm3Z+mWcocqkMqho1qybtSDTMhSP87sWa2vuWdaZY96NSPEQHDdOu6NAn0LEQWsucGt2c6aosTEGW6rgY1bJjFRSg9EN4HdPFHgx2rUUnMcqhUxAqi8g81tP5H0Cy230o7Efyv6Gp0cFy6q6CXb9Dd49fdsMR+ysSLJKtogwRH2tliCUvgHsah3ee5rFEeMX+mlqHdvuxlz0okA51dufcRpVUdQjCWKRnbFo5HqTipxUef8Rz7jRTAeGX+Q==',
//            'buyer_id' => '2088702629366494',
//            'invoice_amount' => '0.01',
//            'notify_id' => '2021071400222163541066491405515691',
//            'fund_bill_list' => '[{"amount":"0.01","fundChannel":"ALIPAYACCOUNT"}]',
//            'notify_type' => 'trade_status_sync',
//            'trade_status' => 'TRADE_SUCCESS',
//            'receipt_amount' => '0.01',
//            'app_id' => '2021002158609803',
//            'buyer_pay_amount' => '0.01',
//            'sign_type' => 'RSA2',
//            'seller_id' => '2088141861767401',
//            'gmt_payment' => '2021-07-14 16:35:40',
//            'notify_time' => '2021-07-14 16:35:41',
//            'version' => '1.0',
//            'out_trade_no' => 'K714517337064400',
//            'total_amount' => '0.01',
//            'trade_no' => '2021071422001466491434820236',
//            'auth_app_id' => '2021002158609803',
//            'buyer_logon_id' => '186****5092',
//            'point_amount' => '0.00',
//        );
        $aliPay = new Alipay();
        $status = $aliPay->notify($getData);
        if($status == true){
            $orderData = Db::name('qt_order')->where('order_no',$getData['out_trade_no'])->find();
            if($orderData['status'] != '1'){
                return 'success';
            }
            $userInfo = Db::name('qt_users')->where('id',$orderData['user_id'])->find();
            //处理有余额的用户
            if(!empty($orderData['yu_deduction'])){
                //增加消费记录
                $moneyData['user_id'] = $userInfo['id'];
                $moneyData['type'] = 1;
                $moneyData['money'] = $orderData['yu_deduction'];
                $moneyData['create_time'] = time();
                $moneyData['content'] = '购物消费';
                $moneyData['check'] = 2;
                $moneyData['flag'] = 1;
                $moneyData['after_money'] = $userInfo['money'] - $orderData['yu_deduction'];
                Db::name('qt_money_log')->insert($moneyData);
                Db::name('qt_users')->where('id',$userInfo['id'])->setDec('money',$orderData['yu_deduction']);
            }

            try{
                Db::startTrans();
                //修改订单状态
                Db::name('qt_order')->where('id',$orderData['id'])->update(['status'=>2,'pay_type'=>3,'pay_time'=>time(),'pay_status'=>2]);
                //增加积分记录
                if($orderData['point'] != 0){
                    $pointData['user_id'] = $userInfo['id'];
                    $pointData['type'] = 1;
                    $pointData['money'] = $orderData['point'];
                    $pointData['create_time'] = time();
                    $pointData['content'] = '购物消费抵扣';
                    $pointData['check'] = 2;
                    $pointData['flag'] = 2;
                    $pointData['after_money'] = $userInfo['point'] - $orderData['point'];
                    Db::name('qt_money_log')->insert($pointData);
                }
                //查找优惠券总的优惠券
                $couId = Db::name('qt_order')->where('id',$orderData['id'])->value('cou_id');
                if($couId){
                    Db::name('qt_coupon_list')->where(['id'=>$couId])->update(['use_time'=>time(),'is_use'=>2]);
                }
                //各个商品的优惠券
                $orderGoodsRes = Db::name('qt_order_goods')->where(['order_id'=>$orderData['id']])->select();
                if(!empty($orderGoodsRes)){
                    foreach ($orderGoodsRes as $key=>$value){
                        //处理优惠券
                        if(!empty($value['cou_id'])){
                            Db::name('qt_coupon_list')->where(['id'=>$value['cou_id']])->update(['use_time'=>time(),'is_use'=>2]);
                        }
                        //增加积分
                        $point = Db::name('qt_goods')->where('goods_id',$value['goods_id'])->value('give_point');
                        $pointInsert['user_id'] = $userInfo['id'];
                        $pointInsert['type'] = 1;
                        $pointInsert['money'] = $point;
                        $pointInsert['create_time'] = time();
                        $pointInsert['content'] = '购物积分赠送';
                        $pointInsert['check'] = '1';
                        $pointInsert['flag'] = '2';
                        $pointInsert['after_money'] = $userInfo['point'] + $point;
                        Db::name('qt_users')->where('id',$userInfo['id'])->setInc('point',$point);
                        Db::name('qt_money_log')->insert($pointInsert);
                        //减少库存
                        Db::name('qt_goods_sku')->where(['id'=>$value['sku_id']])->setDec('stock',$value['num']);
                        //增加销量
                        Db::name('qt_goods')->where(['goods_id'=>$value['goods_id']])->setInc('sale_num',$value['num']);
                    }
                }
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                return "error";
            }
            return "success";
        }

    }


    /**
     * 拼团订单回调
     */
    public function ali_group_order(){
        $getData = $this->request->post();
        $aliPay = new Alipay();
        $status = $aliPay->notify($getData);
        if($status == true){
            $orderData =  Db::name('qt_group_order')->where('order_no',$getData['out_trade_no'])->find();
            $userInfo = Db::name('qt_users')->where('id',$orderData['user_id'])->find();
            //处理有余额的用户
            if(!empty($orderData['yu_deduction'])){
                //增加消费记录
                $moneyData['user_id'] = $userInfo['id'];
                $moneyData['type'] = 1;
                $moneyData['money'] = $orderData['yu_deduction'];
                $moneyData['create_time'] = time();
                $moneyData['content'] = '购物消费';
                $moneyData['check'] = 2;
                $moneyData['flag'] = 1;
                $moneyData['after_money'] = $userInfo['money'] - $orderData['yu_deduction'];
                Db::name('qt_money_log')->insert($moneyData);
                Db::name('qt_users')->where('id',$userInfo['id'])->setDec('money',$orderData['yu_deduction']);
            }
            try{
                Db::startTrans();
                //修改订单状态
                Db::name('qt_group_order')->where('id',$orderData['id'])->update(['status'=>2,'pay_type'=>3,'pay_time'=>time(),'pay_status'=>1]);
                Db::name('qt_group_user')->where('order_num',$orderData['order_no'])->update(['status'=>2]);
                //减少库存
                Db::name('qt_goods_sku')->where('id',$orderData['sku_id'])->setDec('stock',$orderData['number']);
                //增加销量
                Db::name('qt_goods')->where('goods_id',$orderData['goods_id'])->setInc('sale_num',$orderData['number']);
                //查看拼团人数
                $pinNum =  Db::name('qt_group_user')->where('order_num',$orderData['order_no'])->find();
                $use = Db::name('qt_group_user')->where('open_user_id',$pinNum['open_user_id'])->where('status',2)->count();
                //使用人数大于等于拼团人数，更改所有的用户状态
                if($use >= $pinNum['pnum'] ){
                    $updateData = Db::name('qt_group_user')->where('open_user_id',$pinNum['open_user_id'])->where('status',2)->select();
                    foreach ($updateData as $key=>$value){
                        Db::name('qt_group_user')->where('id',$value['id'])->update(['status'=>3]);
                    }
                }
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                return "error";
            }
            return "success";
        }else{
            return "error";
        }
    }

    /**
     * 积分订单回调
     */
    public function ali_point(){
        $getData = $this->request->post();
        $aliPay = new Alipay();
        $status = $aliPay->notify($getData);
        if($status == true){
            $orderData = Db::name('qt_point_order')->where('order_no',$getData['out_trade_no'])->find();
            $userInfo = Db::name('qt_users')->where('id',$orderData['user_id'])->find();
            //处理有余额的用户
            if(!empty($orderData['yu_deduction'])){
                //增加消费记录
                $moneyData['user_id'] = $userInfo['id'];
                $moneyData['type'] = 1;
                $moneyData['money'] = $orderData['yu_deduction'];
                $moneyData['create_time'] = time();
                $moneyData['content'] = '购物消费';
                $moneyData['check'] = 2;
                $moneyData['flag'] = 1;
                $moneyData['after_money'] = $userInfo['money'] - $orderData['yu_deduction'];
                Db::name('qt_money_log')->insert($moneyData);
                Db::name('qt_users')->where('id',$userInfo['id'])->setDec('money',$orderData['yu_deduction']);
            }
            try{
                Db::startTrans();
                //加销量
                Db::name('qt_point')->where('id',$orderData['goods_id'])->setInc('sale_num',$orderData['goods_num']);
                //减少库存
                Db::name('qt_point_sku')->where('id',$orderData['sku_id'])->setDec('sku_stock',$orderData['goods_num']);
                //减少用户积分余额
                Db::name('qt_users')->where('id',$userInfo['id'])->setDec('point',$orderData['total']);
                //修改订单状态
                Db::name('qt_point_order')->where('id',$orderData['id'])->update(['status'=>2,'pay_type'=>1,'pay_time'=>time(),'pay_status'=>2]);
                //增加积分记录
                if($orderData['point'] != 0){
                    $pointData['user_id'] = $userInfo['id'];
                    $pointData['type'] = 1;
                    $pointData['money'] = $orderData['total'];
                    $pointData['create_time'] = time();
                    $pointData['content'] = '购物消费抵扣';
                    $pointData['check'] = 2;
                    $pointData['flag'] = 2;
                    $pointData['after_money'] = $userInfo['point'] - $orderData['point'];
                    Db::name('qt_money_log')->insert($pointData);
                }
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                return 'error';
            }
            return 'success';
        }
        return 'error';
    }

    /**
     * 银联支付回调
     */
    public function union_notify()
    {

    }

    /**
     * 微信会员卡充值回调
     */
    public  function  wx_rechare_notify_url(){
        $input = file_get_contents('php://input', 'r');
        $Wxpay = new Wxpay();
        $payresult = $Wxpay->notify($input);
        $post_data = xml_to_array($input);   //微信支付成功，返回回调地址url的数据：XML转数组Array
        $myfile = fopen("wxpayfile.txt", "a");
        fwrite($myfile, "\r\n");
        fwrite($myfile, $input);
        if ($payresult) {
            $out_trade_no = $post_data['out_trade_no'];
            $order=VipRechargeLog::where('order_no',$out_trade_no)
                ->where('pay_status',1)
                ->find();
            if ($order['pay_status'] == '1') {
                return_success();
            }else{
                if ($order) {
                    $status = array(
                        'pay_type'=>'1',
                        'pay_status' => '2',
                        'pay_time' => time()
                    );
                    //修改订单为已支付
                    VipRechargeLog::where('id', $order['id'])->update($status);
                    //修改记录为已支付
                    CommissionLog::where('type','4')
                        ->where('order_project_id',$order['id'])
                        ->update(['is_pay'=>'2','pay_type'=>'1']);
                    //增加用户的余额
                    $VipcardModel=new ViperCard();
                    $money=$order['amount']+$order['give_amout'];
                    $VipcardModel->change_cardmoney($order['viper_card_id'],$money,'1','1','充值','充值');
                    //赠送积分
                   if($order['integral']!='0'){
                      ViperUser::where('id',$order['user_id'])->inc('integral',$order['integral'])->update();
                   }
                    return_success();
                }
            }
        }else {
            echo '微信支付失败';
        }
    }
    /**
     * 支付宝会员卡充值回调
     */
    public  function  alipay_rechare_notify_url(){
        $arr=$_POST;
        $AliPay=new Alipay();
        $payresult=$AliPay->notify($arr);
        $myfile = fopen("alipayfile2.txt", "a");
        fwrite($myfile, "\r\n");
        if ($payresult) {
            $out_trade_no = $arr['out_trade_no'];
            $order=VipRechargeLog::where('order_no',$out_trade_no)
                ->where('pay_status',1)
                ->find();
            if ($order['pay_status'] == '1') {
                echo 'success';
            }else{
                if ($order) {
                    $status = array(
                        'pay_type'=>'2',
                        'pay_status' => '2',
                        'pay_time' => time()
                    );
                    //修改订单为已支付
                    VipRechargeLog::where('id', $order['id'])->update($status);
                    //修改记录为已支付
                    CommissionLog::where('type','4')
                        ->where('order_project_id',$order['id'])
                        ->update(['is_pay'=>'2','pay_type'=>'2']);
                    //增加用户的余额
                    $VipcardModel=new ViperCard();
                    $money=$order['amount']+$order['give_amout'];
                    $VipcardModel->change_cardmoney($order['viper_card_id'],$money,'1','1','充值','充值');
                    //赠送积分
                    if($order['integral']!='0'){
                        ViperUser::where('id',$order['user_id'])->inc('integral',$order['integral'])->update();
                    }
                    echo 'success';
                }
            }
        }else {
            echo 'fail';
        }
    }

    /**
     * 微信项目支付回调
     */
    public  function  wx_pj_notify_url(){
        $input = file_get_contents('php://input', 'r');
        $Wxpay = new Wxpay();
        $payresult = $Wxpay->notify($input);
        $post_data = xml_to_array($input);   //微信支付成功，返回回调地址url的数据：XML转数组Array
        $myfile = fopen("wxpayfile.txt", "a");
        fwrite($myfile, "\r\n");
        fwrite($myfile, $input);
        if ($payresult) {
            $out_trade_no = $post_data['out_trade_no'];
            $order=\app\common\model\Order::where('pay_no',$out_trade_no)
                ->where('pay_status',1)
                ->find();
            if ($order['pay_status'] == '2') {
                return_success();
            }else{
                if ($order) {
                    $status = array(
                        'pay_type'=>'1',
                        'pay_status' => '2',
                        'pay_time' => time()
                    );
                    Order::where('id',$order['id'])->update($status);
                    $order_project=Orderproject::where('order_id',$order['id'])->column('id');
                    CommissionLog::where('type','1')->whereIn('order_project_id',$order_project)->update(['is_pay'=>'2','pay_type'=>'1']);
                    return_success();
                }
            }
        }else {
            echo '微信支付失败';
        }

    }
    /**
     * 支付宝项目支付回调
     */
    public  function  alipay_pj_notify_url(){
        $arr=$_POST;
        $AliPay=new Alipay();
        $payresult=$AliPay->notify($arr);
        $myfile = fopen("alipayfile2.txt", "a");
        fwrite($myfile, "\r\n");
        if ($payresult) {
            $out_trade_no = $arr['out_trade_no'];
            $order=\app\common\model\Order::where('pay_no',$out_trade_no)
                ->where('pay_status',1)
                ->find();
            if ($order['pay_status'] == '1') {
                echo 'success';
            }else{
                if ($order) {
                    $status = array(
                        'pay_type'=>'2',
                        'pay_status' => '2',
                        'pay_time' => time()
                    );
                    Order::where('id',$order['id'])->update($status);
                    $order_project=Orderproject::where('order_id',$order['id'])->column('id');
                    CommissionLog::where('type','1')->whereIn('order_project_id',$order_project)->update(['is_pay'=>'2','pay_type'=>'2']);
                    return_success();
                }

            }
        }else {
            echo 'fail';
        }

    }
}
